package com.demo.project_template.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.demo.project_template.entity.UserGoldRecord;
import com.demo.project_template.entity.UserWallet;
import com.demo.project_template.exception.ErrorCodeException;
import com.demo.project_template.mapper.UserGoldRecordMapper;
import com.demo.project_template.mapper.UserWalletMapper;
import com.demo.project_template.service.UserGoldRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 金币变动记录表 服务实现类
 * </p>
 *
 * @author 杨玉龙
 * @since 2024-08-20 18:10:02
 */
@Service
@Transactional
public class UserGoldRecordServiceImpl extends ServiceImpl<UserGoldRecordMapper, UserGoldRecord> implements UserGoldRecordService {
    @Resource
    private UserWalletMapper userWalletMapper;

    @Override
    public synchronized void add(UserGoldRecord userGoldRecord){
        UserWallet userWallet = userWalletMapper.selectOne(new LambdaQueryWrapper<UserWallet>().eq(UserWallet::getUserId, userGoldRecord.getUserId()));
        if ("1".equals(userGoldRecord.getIsAdd())){
            //增加金币
            userWallet.setGoldCount(userWallet.getGoldCount()+userGoldRecord.getAmount());
        }else {
            //减少金币
            if (userWallet.getGoldCount()<userGoldRecord.getAmount()){
                throw new ErrorCodeException("金币不足");
            }
            userWallet.setGoldCount(userWallet.getGoldCount()-userGoldRecord.getAmount());
        }
        int i = userWalletMapper.updateById(userWallet);
        if (i<1){
            throw new ErrorCodeException("操作异常，请重新操作");
        }
        save(userGoldRecord);
    }
}
